package com.feeyo.groundservice.checkin.fragment.view

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.VerticalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableIntState
import androidx.compose.runtime.MutableLongState
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInParent
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ScreenUtils
import com.feeyo.groundservice.base_util.FyLog
import com.feeyo.groundservice.base_util.SuccessCallback
import com.feeyo.groundservice.base_util.delayMillToExecute
import com.feeyo.groundservice.base_util.formatTimeHM
import com.feeyo.groundservice.base_util.formatTimeMD
import com.feeyo.groundservice.base_util.formatTimeYMD
import com.feeyo.groundservice.base_util.getDayFromYMD
import com.feeyo.groundservice.base_util.getNextDay
import com.feeyo.groundservice.base_util.getPreDay
import com.feeyo.groundservice.base_util.getRouterPath
import com.feeyo.groundservice.base_util.toSeconds
import com.feeyo.groundservice.base_util.toastCenter
import com.feeyo.groundservice.checkin.R
import com.feeyo.groundservice.checkin.base.refreshState
import com.feeyo.groundservice.checkin.constant.CheckInPath
import com.feeyo.groundservice.checkin.constant.CheckInSortType
import com.feeyo.groundservice.checkin.constant.CheckInStatusType
import com.feeyo.groundservice.checkin.constant.checkInListRefreshFlag
import com.feeyo.groundservice.checkin.constant.checkInSortType
import com.feeyo.groundservice.checkin.constant.checkInTask
import com.feeyo.groundservice.checkin.constant.checkInTaskTemp
import com.feeyo.groundservice.checkin.constant.checkInUser
import com.feeyo.groundservice.checkin.constant.checkInUserRefreshFlag
import com.feeyo.groundservice.checkin.constant.clearData
import com.feeyo.groundservice.checkin.constant.currentFilterCheckInList
import com.feeyo.groundservice.checkin.constant.currentLetter
import com.feeyo.groundservice.checkin.constant.dataInitFinishedFlag
import com.feeyo.groundservice.checkin.constant.getCheckInTabMenus
import com.feeyo.groundservice.checkin.constant.getCheckInTimes
import com.feeyo.groundservice.checkin.constant.getNextSortType
import com.feeyo.groundservice.checkin.constant.initScrollFinishedFlag
import com.feeyo.groundservice.checkin.constant.linkUserTask
import com.feeyo.groundservice.checkin.constant.openDetailData
import com.feeyo.groundservice.checkin.constant.resetFlag
import com.feeyo.groundservice.checkin.constant.showAddCheckInPop
import com.feeyo.groundservice.checkin.constant.showCheckInDetailRightAttach
import com.feeyo.groundservice.checkin.constant.statusBarColor
import com.feeyo.groundservice.checkin.model.CheckInTimeBO
import com.feeyo.groundservice.checkin.model.LinkUserTaskBO
import com.feeyo.groundservice.checkin.viewmodel.CheckInViewModel
import com.feeyo.groundservice.composewidget.util.EmptyListView
import com.feeyo.groundservice.composewidget.util.dimenToDp
import com.feeyo.groundservice.composewidget.util.dimenToSp
import com.feeyo.groundservice.composewidget.util.dpToPx
import com.feeyo.groundservice.composewidget.util.drawableToPainter
import com.feeyo.groundservice.composewidget.util.intervalClick
import com.feeyo.groundservice.composewidget.util.pxToDp
import com.feeyo.groundservice.composewidget.util.toComposeColor
import com.feeyo.groundservice.composewidget.view.calendar.BottomCalendar
import com.feeyo.groundservice.composewidget.view.refreshlayout.PullToRefreshLayout
import com.feeyo.groundservice.composewidget.view.refreshlayout.rememberRefreshLayoutState
import com.feeyo.groundservice.composewidget.view.tab.SwitchTab
import com.feeyo.groundservice.composewidget.view.tab.TabCountPosition
import com.feeyo.groundservice.composewidget.view.util.HorizontalSpace
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 *作者：70893 on 2025-10-23
 *描述：
 */

@Composable
internal fun CheckInMainView(
    currentDate: MutableLongState,
    topPadding: Dp,
    showDatePicker: () -> Unit
) {
    val resetLetter = remember { mutableLongStateOf(System.currentTimeMillis()) }
    val viewModel: CheckInViewModel = viewModel()

    val defaultIndex = CheckInStatusType.ALL.code
    val mCurrentSelectTab = remember { mutableStateOf(CheckInStatusType.ALL) }

    Column(
        modifier = Modifier.fillMaxSize().padding(top = topPadding)
    ) {

        Box() {
            Column(
                modifier = Modifier.fillMaxSize()
            ) {
                //tab
                CheckInTabView(
                    onSelectPerson = {
                        CheckInPath.CheckInPersonSelectActivity.getRouterPath().navigation()
                    },
                    mCurrentSelectTab = mCurrentSelectTab,
                    defaultIndex = defaultIndex
                )
                //人员和任务
                CheckInListView(
                    currentDate = currentDate,
                    currentIndexTab = mCurrentSelectTab
                )
            }

            //日历
            BottomCalendar(
                //根据选择的时间类型 自然日 生产日分别计算显示的日期
                time = currentDate.longValue.formatTimeYMD().getDayFromYMD(),
                onPre = { //前一天
                    resetFlag()
                    currentDate.longValue = currentDate.longValue.getPreDay().toSeconds()
                },
                onCalendar = {
                    showDatePicker()
                },
                onNext = { //后一天
                    resetFlag()
                    currentDate.longValue = currentDate.longValue.getNextDay().toSeconds()
                },
                onRefresh = {//刷新按钮
                    checkInListRefreshFlag.longValue = System.currentTimeMillis()
                },
                modifier = Modifier.align(Alignment.BottomEnd)
                    .padding(bottom = R.dimen.d10.dimenToDp(), end = R.dimen.d15.dimenToDp())
            )

            //字母筛选器
            Column(
                modifier = Modifier.align(Alignment.TopEnd)
                    .padding(top = R.dimen.d80.dimenToDp())
            ) {
                Box(
                    modifier = Modifier.size(
                        R.dimen.d30.dimenToDp(),
                        R.dimen.d18.dimenToDp()
                    ).intervalClick {
                        resetLetter.longValue = System.currentTimeMillis()
                        currentLetter.value = "#"
                    },
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "重置",
                        fontSize = R.dimen.d12.dimenToSp(),
                        fontWeight = FontWeight.W400,
                        color = R.color.black_33.toComposeColor(),
                    )
                }

                Card(
                    elevation = CardDefaults.elevatedCardElevation(defaultElevation = R.dimen.d5.dimenToDp()),
                    shape = RoundedCornerShape(R.dimen.d2.dimenToDp()),
                    colors = CardDefaults.elevatedCardColors(containerColor = R.color.white.toComposeColor())
                ) {
                    LetterSelectorView(
                        resetFlag = resetLetter,
                        onSelectLetter = {
                            currentLetter.value = it
                        }
                    )
                }
            }
        }
    }

    //日期切换
    LaunchedEffect(key1 = currentDate.longValue) {
        //刷新人员+任务
        checkInTaskTemp?.let {
            viewModel.getCheckInUserList(currentDate.longValue, object : SuccessCallback {
                override fun success() {
                    super.success()
                    //获取值机任务列表
                    viewModel.getCheckInList(
                        currentDate.longValue,
                        object : SuccessCallback {
                            override fun success() {
                                super.success()
                                //关联人员和任务
                                val links = arrayListOf<LinkUserTaskBO>()
                                checkInUser?.forEach { person ->
                                    val task = checkInTask?.firstOrNull {
                                        it.user.uid == person.uid
                                    }
                                    links.add(LinkUserTaskBO(person, task))
                                }
                                //绑定人员和任务，刷新UI
                                linkUserTask.value = links
                                //可以进行滚动设置了
                                dataInitFinishedFlag.value = true
                                FyLog.e("CheckInMainView", "日期切换数据刷新完成")

                            }
                        })
                }
            })
        }
    }

    //值机人员列表
    LaunchedEffect(checkInUserRefreshFlag.longValue) {
        //刷新人员
        checkInTaskTemp?.let {
            viewModel.getCheckInUserList(currentDate.longValue, object : SuccessCallback {
                override fun success() {
                    super.success()
                    //关联人员和任务
                    val links = arrayListOf<LinkUserTaskBO>()
                    checkInUser?.forEach { person ->
                        val task = checkInTask?.firstOrNull {
                            it.user.uid == person.uid
                        }
                        links.add(LinkUserTaskBO(person, task))
                    }
                    //绑定人员和任务，刷新UI
                    linkUserTask.value = links
                    //可以进行滚动设置了
                    dataInitFinishedFlag.value = true
                    FyLog.e("CheckInMainView", "人员更新数据刷新完成")

                }
            })


        }
    }

    //新增值机，下拉刷新，手动刷新
    LaunchedEffect(key1 = checkInListRefreshFlag.longValue) {
        //刷新任务
        checkInTaskTemp?.let {
            //获取值机任务列表
            viewModel.getCheckInList(
                currentDate.longValue,
                object : SuccessCallback {
                    override fun success() {
                        super.success()
                        //关联人员和任务
                        val links = arrayListOf<LinkUserTaskBO>()
                        checkInUser?.forEach { person ->
                            val task = checkInTask?.firstOrNull {
                                it.user.uid == person.uid
                            }
                            links.add(LinkUserTaskBO(person, task))
                        }
                        //绑定人员和任务，刷新UI
                        linkUserTask.value = links
                        FyLog.e("CheckInMainView", "值机列表数据刷新完成")
                    }
                })
        }
    }

    //初始化的
    DisposableEffect(Unit) {
        //获取系统配置值机任务模板，一般只有一个，以及人员和任务列表
        viewModel.getSysConfig()
        onDispose {
            clearData()
        }
    }

    //任务详情刷新
    LaunchedEffect(key1 = linkUserTask.value) {

        //如果详情页打开，更新一下详情页的数据项
        openDetailData.value?.let { currentData ->
            FyLog.e("CheckInMainView", "更新值机详情数据")
            openDetailData.value =
                linkUserTask.value?.firstOrNull { it.user.uid == currentData.user.uid }
        }
    }
}

@Composable
internal fun CheckInTabView(
    onSelectPerson: () -> Unit,
    defaultIndex: Int,
    mCurrentSelectTab: MutableState<CheckInStatusType>,
) {
    //导航tab
    val titles = remember { getCheckInTabMenus() }

    //tab
    Row(
        modifier = Modifier.background(color = statusBarColor.toComposeColor())
            .padding(vertical = R.dimen.d5.dimenToDp()),
        verticalAlignment = Alignment.CenterVertically
    ) {
        HorizontalSpace(R.dimen.d15.dimenToDp())
        SwitchTab(
            tabRowItems = titles,
            onSelectIndex = {
                mCurrentSelectTab.value = CheckInStatusType.getType(it)
            },
            defaultIndex = defaultIndex,
            bottomHeight = R.dimen.d36.dimenToDp(),
            bottomBgColor = R.color.transparent.toComposeColor(),
            bottomCornerRadius = 0.dp,
            selectedTextColor = R.color.white.toComposeColor(),
            unSelectedTextColor = R.color.white.toComposeColor().copy(alpha = 0.6f),
            selectedTextSize = R.dimen.d13.dimenToDp(),
            unSelectedTextSize = R.dimen.d12.dimenToDp(),
            padding = 0.dp,
            tabCountDirection = TabCountPosition.BOTTOM,
            slideBarGapWidth = R.dimen.d4.dimenToDp(),
            slideBarWidth = R.dimen.d52.dimenToDp(),
            slideBarBgColor = R.color.white.toComposeColor().copy(alpha = 0.15f),
            slideBarCornerRadius = R.dimen.d4.dimenToDp(),
        )
        Spacer(modifier = Modifier.weight(1f))
        //人员设置
        Icon(
            painter = R.drawable.icon_check_in_person_setting.drawableToPainter(),
            contentDescription = null,
            tint = R.color.white.toComposeColor(),
            modifier = Modifier.size(R.dimen.d24.dimenToDp())
                .intervalClick {
                    onSelectPerson()
                }
        )
        HorizontalSpace(R.dimen.d15.dimenToDp())
    }

    //更新当班数量
    LaunchedEffect(key1 = checkInUser) {
        titles.last().count?.value = checkInUser?.filter { it.isDuty }?.size ?: 0
    }

    //筛选结果后进行重新计算数量
    LaunchedEffect(key1 = currentFilterCheckInList.value) {
        currentFilterCheckInList.value?.let { checkInList ->
            titles.forEach {
                when (it.title) {
                    CheckInStatusType.ALL.title -> it.count?.value = checkInList.size
                    CheckInStatusType.CHECKING_IN.title -> {//值机中，有开始的值机任务
                        it.count?.value = checkInList.filter {
                            //存在任何一个开始的任务
                            it.task?.task_list?.any { it.task.isStart && !it.task.isEnd } ?: false
                        }.size
                    }

                    CheckInStatusType.WAIT_CHECK_IN.title -> {
                        it.count?.value = checkInList.filter {
                            //所有任务都是未开始
                            it.task?.task_list?.all { !it.task.isStart } ?: false
                        }.size
                    }

                    CheckInStatusType.FREE.title -> {
                        //没有任务以及没有未完成的任务的人
                        it.count?.value = checkInList.filter {
                            it.task == null || it.task?.task_list?.all { it.task.isEnd } == true
                        }.size
                    }

                    CheckInStatusType.DANG_BAN.title -> {
                        it.count?.value = checkInList.filter {
                            it.user.isDuty
                        }.size
                    }
                }
            }
        }
    }
}

@Composable
internal fun CheckInListView(
    currentDate: MutableLongState,
    currentIndexTab: MutableState<CheckInStatusType>,
) {

    //计算日期刻度列表，以分钟为最小单位刻度
    val times = remember(currentDate.longValue) { getCheckInTimes(currentDate.longValue) }
    //当前时间刻度线位置，外部参考日期变了重新计算
    val currentTimeLine =
        remember(currentDate.longValue) { mutableLongStateOf(currentDate.longValue) }
    //水平滚动状态：关联人员列表和任务列表
    val horizontalScrollState = rememberScrollState()
    //垂直滚动状态: 关联时间刻度列表和任务列表
    val verticalScrollState = rememberScrollState()
    //人员列表宽度
    val personWidth = R.dimen.d50.dimenToDp()
    //时间刻度高度
    val timeHeight = R.dimen.d34.dimenToDp()
    //每一个时间大刻度之间的间距
    val itemWidth = R.dimen.d60.dimenToDp().dpToPx()
    val totalWidth = remember { mutableFloatStateOf(itemWidth * times.size) }

    Box(
        modifier = Modifier.fillMaxSize()
    ) {
        Column(
            Modifier.fillMaxSize()
        ) {
            //值班员+刻度
            Row(
                modifier = Modifier.fillMaxWidth().height(timeHeight)
                    .background(color = R.color.gray_E7EBF1.toComposeColor()),
            ) {

                Box(
                    modifier = Modifier.width(personWidth).height(timeHeight)
                        .intervalClick {
                            //值机员可点击按值机时长正序或倒序排序， 最后一次点击恢复默认排序
                            checkInSortType.value = checkInSortType.value.getNextSortType()
                        },
                    contentAlignment = Alignment.Center
                ) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "值机员",
                            fontSize = R.dimen.d12.dimenToSp(),
                            fontWeight = FontWeight.W400,
                            color = R.color.black_66.toComposeColor(),
                        )

                        val icon = when (checkInSortType.value) {
                            CheckInSortType.CHECK_IN_TIME_ASC -> R.drawable.icon_asc_sort.drawableToPainter()
                            CheckInSortType.CHECK_IN_TIME_DESC -> R.drawable.icon_desc_sort.drawableToPainter()
                            else -> null
                        }
                        icon?.let {
                            HorizontalSpace(R.dimen.d5.dimenToDp())
                            Icon(
                                painter = it,
                                contentDescription = null,
                                modifier = Modifier.height(R.dimen.d12.dimenToDp()),
                                tint = statusBarColor.toComposeColor(),
                            )
                        }
                    }

                }

                //时间刻度
                Row(
                    modifier = Modifier
                        .width(totalWidth.floatValue.pxToDp()).height(timeHeight)
                        .background(color = R.color.gray_ECEFF4.toComposeColor())
                        .horizontalScroll(horizontalScrollState),
                    horizontalArrangement = Arrangement.spacedBy(R.dimen.d40.dimenToDp()),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    times.forEachIndexed { index, timeBO ->
                        TimeItemView(index, timeBO)
                    }
                }
            }


            PullToRefreshLayout(
                modifier = Modifier.weight(1f).fillMaxHeight(),
                refreshLayoutState = rememberRefreshLayoutState {
                    //编写刷新逻辑
                    refreshState = this
                    checkInListRefreshFlag.longValue = System.currentTimeMillis()
                }
            ) {
                //人员列表+任务列表
                CoordinatedScrollView(
                    personWidth = personWidth,
                    totalWidth.floatValue.pxToDp(),
                    times[0].time,
                    times[1].position / 3600f,
                    horizontalScrollState = horizontalScrollState,
                    verticalScrollState = verticalScrollState,
                    currentIndexTab = currentIndexTab
                )
            }
        }

        //时间刻度线
        Column(
            modifier = Modifier.align(Alignment.TopCenter).padding(top = timeHeight / 2),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Box(
                modifier = Modifier.width(R.dimen.d36.dimenToDp()).height(timeHeight / 2)
                    .background(
                        color = R.color.red_FF3141.toComposeColor(),
                        shape = CircleShape
                    ).intervalClick {
                        //回到当前时间线位置
                        currentTimeLine.longValue = currentDate.longValue//日期所在的时间线
                    },
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = currentTimeLine.longValue.formatTimeHM(),
                    fontSize = R.dimen.d10.dimenToSp(),
                    fontWeight = FontWeight.W400,
                    color = R.color.white.toComposeColor()
                )
            }

            VerticalDivider(
                modifier = Modifier.fillMaxHeight(),
                thickness = R.dimen.d1.dimenToDp(),
                color = R.color.red_FF3141.toComposeColor()
            )

        }
    }

    val isScrolling = remember { mutableStateOf(false) }

    LaunchedEffect(key1 = dataInitFinishedFlag.value, key2 = currentTimeLine.longValue) {
        if (!dataInitFinishedFlag.value) return@LaunchedEffect
        if (isScrolling.value) return@LaunchedEffect
        FyLog.e("CheckInMainView", "开始初始化滚动")
        //单位
        val distance = itemWidth//times[1].position
        //当前时间刻度线位置距离起始位置的增量,每一个大刻度为3600秒，为一个小时
        val currentPositionIncrease = (currentTimeLine.longValue - times.first().time)
        //偏移的差值，计算移到中间的偏差[减去左边的人员宽度d70]
        val diffOffset = ScreenUtils.getAppScreenWidth() / 2 - distance * 70 / 60f
        //滑块的偏移值 d36
        val sliderOffset = distance * 18 / 60f
        //重新计算总宽度
        totalWidth.floatValue = distance * times.size
        //根据当前时间，计算当前时间刻度线位置,px
        val offset =
            distance * currentPositionIncrease / 3600f - diffOffset - sliderOffset - 6

        horizontalScrollState.scrollTo(offset.toInt())

        delayMillToExecute(3000) {
            //延迟3秒，初始化完成，跳过初始化时的滚动监听响应问题
            initScrollFinishedFlag.value = true
        }
    }

    //当滑动的时候，重置当前时间线显示
    LaunchedEffect(horizontalScrollState.value) {
        if (initScrollFinishedFlag.value) {
            val distance = itemWidth//times[1].position
            //偏移的差值，计算移到中间的偏差[减去左边的人员宽度d70]
            val diffOffset = ScreenUtils.getAppScreenWidth() / 2 - distance * 70 / 60f
            //滑块的偏移值 d36
            val sliderOffset = distance * 18 / 60f
            isScrolling.value = true
            currentTimeLine.longValue =
                times[0].time + ((3600f / distance) * (horizontalScrollState.value + diffOffset + sliderOffset + 6)).toLong()

            FyLog.e("CheckInMainView", "滚动了")
            //延迟,在滚动的时候不触发时间线变更引发的附带效应
            launch {
                delay(300)
                isScrolling.value = false
            }
        }
    }


}

@Composable
private fun TimeItemView(index: Int, item: CheckInTimeBO) {
    Column(
        modifier = Modifier.onGloballyPositioned { layoutCoordinates ->
            if (index == 1) {
                val p = layoutCoordinates.positionInParent()
                item.position = p.x
            }

        }
    ) {
        Text(
            text = if (item.timeH == "00") item.time.formatTimeMD() else "",
            fontSize = R.dimen.d9.dimenToSp(),
            fontWeight = FontWeight.W400,
            color = R.color.black_66.toComposeColor(),
        )
        Box(
            modifier = Modifier.width(R.dimen.d20.dimenToDp()).height(R.dimen.d18.dimenToDp())
                .background(
                    color = R.color.black.toComposeColor().copy(0.1f),
                    shape = RoundedCornerShape(R.dimen.d2.dimenToDp())
                ),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = item.timeH,
                fontSize = R.dimen.d12.dimenToSp(),
                fontWeight = FontWeight.W400,
                color = R.color.black_66.toComposeColor(),
            )
        }


    }

}


/***
 * 人员列表+值机任务列表
 *
 * @param personWidth 人员宽度
 * @param totalWidth 总宽度
 * @param startT 参考的起始时间
 * @param step 每个像素代表的时间长度
 * @param horizontalScrollState 水平滚动状态
 * @param verticalScrollState 垂直滚动状态
 *
 * **/
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun CoordinatedScrollView(
    personWidth: Dp,
    totalWidth: Dp,
    startT: Long,
    step: Float,
    horizontalScrollState: ScrollState,
    verticalScrollState: ScrollState,
    currentIndexTab: MutableState<CheckInStatusType>,
) {
    //每行高度
    val itemHeight = R.dimen.d40.dimenToDp()

    val link = linkUserTask.value ?: emptyList()
    if (link.isEmpty())
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            EmptyListView(tip = "请设置人员")
        }
    else
        link.filter {
            //字母表过滤
            if (currentLetter.value == "#")
                true
            else
                it.user.pinyin.first().uppercase() == currentLetter.value

        }.let {
            //点击值机人员进行排序
            when (checkInSortType.value) {
                CheckInSortType.DEFAULT -> it
                CheckInSortType.CHECK_IN_TIME_ASC -> it.sortedBy { it.task?.checked_time }
                CheckInSortType.CHECK_IN_TIME_DESC -> it.sortedByDescending { it.task?.checked_time }
            }
        }.let {
            currentFilterCheckInList.value = it
            //根据tab返回具体的数据
            val targetList = when (currentIndexTab.value) {
                CheckInStatusType.ALL -> it

                CheckInStatusType.CHECKING_IN -> it.filter {
                    //存在任何一个开始的任务
                    it.task?.task_list?.any { it.task.isStart && !it.task.isEnd } ?: false
                }

                CheckInStatusType.WAIT_CHECK_IN -> it.filter {
                    //所有任务都是未开始
                    it.task?.task_list?.all { !it.task.isStart } ?: false
                }

                CheckInStatusType.FREE -> it.filter {
                    it.task == null || it.task?.task_list?.all { it.task.isEnd } == true
                }

                CheckInStatusType.DANG_BAN -> it.filter { it.user.isDuty }
            }


            Row(modifier = Modifier.fillMaxSize()) {
                //人员
                Column(
                    Modifier.width(personWidth).fillMaxHeight()
                        .verticalScroll(verticalScrollState),
                ) {
                    targetList.forEachIndexed { index, item ->
                        Box(
                            modifier = Modifier.fillMaxWidth().height(itemHeight)
                                .combinedClickable(
                                    onLongClick = {
                                        if (item.user.enable.value) {
                                            ActivityUtils.getTopActivity()
                                                ?.showAddCheckInPop(item.user)
                                        } else {
                                            toastCenter("人员不可用，不能新建值机")
                                        }
                                    },
                                    onClick = {
                                        openDetailData.value = item
                                        ActivityUtils.getTopActivity()
                                            ?.showCheckInDetailRightAttach()
                                    }),
                            contentAlignment = Alignment.Center
                        ) {
                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {
                                Text(
                                    text = item.user.username,
                                    fontSize = R.dimen.d14.dimenToSp(),
                                    fontWeight = FontWeight.W500,
                                    color = R.color.green_06B860.toComposeColor(),
                                )

                                val time = item.task?.totalTime ?: "0分钟"
                                Text(
                                    text = time,
                                    fontSize = R.dimen.d11.dimenToSp(),
                                    fontWeight = FontWeight.W400,
                                    color = R.color.black_33.toComposeColor().copy(0.55f),
                                )
                            }

                            //不可用
                            if (!item.user.enable.value) {
                                Icon(
                                    painter = R.drawable.icon_un_enable.drawableToPainter(),
                                    contentDescription = null,
                                    modifier = Modifier.size(R.dimen.d24.dimenToDp()),
                                    tint = R.color.gray_88.toComposeColor()
                                )
                            }
                        }

                        HorizontalDivider(
                            modifier = Modifier.fillMaxWidth(),
                            thickness = R.dimen.d1.dimenToDp(),
                            color = R.color.gray_D8.toComposeColor()
                        )
                    }
                }

                Box(
                    modifier = Modifier.weight(1f).fillMaxHeight()
                        .verticalScroll(verticalScrollState)
                        .horizontalScroll(horizontalScrollState)
                ) {
                    // 内容
                    CheckInTaskView(totalWidth, itemHeight, startT, step, targetList)
                }
            }
        }
}

@Composable
private fun CheckInTaskView(
    totalWidth: Dp,
    itemHeight: Dp,
    startT: Long,
    step: Float,
    link: List<LinkUserTaskBO>
) {
    val currentTime = System.currentTimeMillis().toSeconds()
    // 实现一个既宽又高的内容区域
    Column(
        modifier = Modifier.width(totalWidth)
            .fillMaxHeight()//就算没数据，也给设置最大宽度，这样可以实现滚动，不然没数据，不会滚到当前时间线
    ) {
        link.forEachIndexed { index, it ->
            Row(
                modifier = Modifier.width(totalWidth).height(itemHeight)
                    .intervalClick {
                        openDetailData.value = it
                        ActivityUtils.getTopActivity()?.showCheckInDetailRightAttach()
                    }
            ) {
                Box(
                    modifier = Modifier.width(totalWidth).height(itemHeight),
                    contentAlignment = Alignment.CenterStart
                ) {
                    //绘制每一个人的值机任务
                    it.task?.task_list?.forEach {
                        //每一个值机柜台任务，按照时间刻度进行排列
                        //根据起始时间计算偏移量
                        val offset = (it.task.startTime - startT) * step
                        //如果当前时间在开始和结束之间，则分割方块，左边绿色右边蓝色
                        //灰色是完成的
                        //绿色是正在执行的
                        //蓝色的是已分配但是未开始的
                        if (it.task.startTime < currentTime && it.task.endTime > currentTime) { //刚好在时间段内
                            val allWidth = (it.task.endTime - it.task.startTime) * step
                            //底部蓝色
                            Box(
                                modifier = Modifier.width(allWidth.pxToDp())
                                    .height(R.dimen.d28.dimenToDp())
                                    .offset(x = offset.pxToDp())
                                    .background(color = R.color.blue_2E76EE.toComposeColor()),
                            ) {
                                val width = (currentTime - it.task.startTime) * step
                                Box(
                                    modifier = Modifier.width(width.pxToDp())
                                        .height(R.dimen.d28.dimenToDp())
                                        .background(color = R.color.green_06B860.toComposeColor()),
                                )

                                Text(
                                    text = it.focus_data.focus_info,
                                    fontSize = R.dimen.d16.dimenToSp(),
                                    fontWeight = FontWeight.W500,
                                    color = R.color.white.toComposeColor(),
                                    modifier = Modifier.align(Alignment.Center)
                                )

                            }

                        } else if (it.task.endTime < currentTime) { //已完成:灰色
                            val width = (it.task.endTime - it.task.startTime) * step
                            Box(
                                modifier = Modifier.width(width.pxToDp())
                                    .height(R.dimen.d28.dimenToDp())
                                    .offset(x = offset.pxToDp())
                                    .background(color = R.color.black.toComposeColor().copy(0.1f)),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = it.focus_data.focus_info,
                                    fontSize = R.dimen.d16.dimenToSp(),
                                    fontWeight = FontWeight.W500,
                                    color = R.color.black_33.toComposeColor(),

                                    )
                            }

                        } else if (it.task.startTime > currentTime) {//未开始的
                            val width = (it.task.endTime - it.task.startTime) * step
                            Box(
                                modifier = Modifier.width(width.pxToDp())
                                    .height(R.dimen.d28.dimenToDp())
                                    .offset(x = offset.pxToDp())
                                    .background(color = statusBarColor.toComposeColor()),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = it.focus_data.focus_info,
                                    fontSize = R.dimen.d16.dimenToSp(),
                                    fontWeight = FontWeight.W500,
                                    color = R.color.white.toComposeColor(),
                                )
                            }
                        }
                    }
                }

            }

            HorizontalDivider(
                modifier = Modifier.width(totalWidth),
                thickness = R.dimen.d1.dimenToDp(),
                color = R.color.gray_D8.toComposeColor()
            )
        }
    }
}